package com.yuhao.init.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuhao.init.common.BaseResponse;
import com.yuhao.init.common.ErrorCode;
import com.yuhao.init.common.ResultUtils;
import com.yuhao.init.config.MinioConfig;
import com.yuhao.init.constant.FileConstant;
import com.yuhao.init.exception.BusinessException;
import com.yuhao.init.mapper.WallPaperClassifyMapper;
import com.yuhao.init.mapper.WallpaperMapper;
import com.yuhao.init.model.dto.wallpaper.RequestWallPaper;
import com.yuhao.init.model.entity.WallPaper;
import com.yuhao.init.model.entity.WallPaperClassify;
import com.yuhao.init.model.vo.PageResultVo;
import com.yuhao.init.model.vo.WallPaperVo;
import com.yuhao.init.service.WallpaperService;
import com.yuhao.init.utils.MinioUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @Author: yuhao
 * @Date: 2024/5/3 13:47
 */

@RestController
@RequestMapping("/wallpaper")
@Slf4j
public class WallPaperController {


    @Autowired
    private MinioUtil minioUtil;

    @Autowired
    private MinioConfig minioConfig;

    @Resource
    private WallpaperMapper wallpaperMapper;

    @Resource
    private WallPaperClassifyMapper wallPaperClassifyMapper;

    /**
     * 文件上传
     *
     * @param multipartFile
     * @return
     */
    @PostMapping("/upload")
    public BaseResponse uploadFile(@RequestPart("file") MultipartFile multipartFile) throws IOException {
        //校验图片是否符合规范
        Boolean validFile = validFile(multipartFile);
        if (!validFile) return ResultUtils.error(ErrorCode.OPERATION_ERROR, "文件不符合要求");
        String objectName = minioUtil.upload(multipartFile, "wallpaper");
        if (null == objectName) {
            return ResultUtils.error(ErrorCode.OPERATION_ERROR, "上传失败");
        }
        String picurl = FileConstant.COS_HOST + "/" + minioConfig.getBucketName() + "/" + objectName;
        log.info("上传成功，url为:{}", picurl);
        return ResultUtils.success(picurl, "上传成功");
    }

    @PostMapping("/add")
    public BaseResponse addWallPaper(@RequestBody RequestWallPaper requestWallPaper) {

        if (requestWallPaper == null) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "数据为空");
        }
        if (StringUtils.isBlank(requestWallPaper.getSmallPicurl()) || StringUtils.isBlank(String.valueOf(requestWallPaper.getClassid()))) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "图片或者分类不能为空");
        }
        WallPaper wallPaper = new WallPaper();
        wallPaper.setClassid(requestWallPaper.getClassid());
        wallPaper.setNickname(requestWallPaper.getNickname());
        wallPaper.setSmallPicurl(requestWallPaper.getSmallPicurl());
        wallPaper.setTabs(requestWallPaper.getTabs());
        wallPaper.setDescription(requestWallPaper.getDescription());
        int insert = wallpaperMapper.insert(wallPaper);
        return ResultUtils.success(null, insert > 0 ? "添加成功" : "添加失败");
    }

    @GetMapping("/list/page")
    public BaseResponse<PageResultVo<WallPaperVo>> listWallPapers(Long pageSize, Long currentPage, @RequestParam(value = "classid",required = false) Long classId) {
        LambdaQueryWrapper<WallPaper> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (classId != null && classId > 0) {
            lambdaQueryWrapper.eq(WallPaper::getClassid, classId);
        }
        Long total = wallpaperMapper.selectCount(null);
        if (pageSize == null || currentPage == null || pageSize.intValue()<0 || currentPage.intValue()<0) {
            pageSize = 10L;
            currentPage = 1L;
        }
        Page<WallPaper> page = wallpaperMapper.selectPage(new Page<>(currentPage, pageSize), lambdaQueryWrapper);
        List<WallPaper> wallPaperList = page.getRecords();
        List<WallPaperVo> records = wallPaperList.stream().map((wallPaper -> {
            WallPaperVo wallPaperVo = new WallPaperVo();
            BeanUtil.copyProperties(wallPaper, wallPaperVo);
            String classifyName = wallPaperClassifyMapper.selectById(wallPaper.getClassid()).getName();
            wallPaperVo.setClassifyName(classifyName);
            String[] split = wallPaper.getTabs().split(",");
            wallPaperVo.setTabs(Arrays.asList(split));
            return wallPaperVo;
        })).collect(Collectors.toList());
        return ResultUtils.success(new PageResultVo<>(total, records));
    }

    /***
     * 随机获取9张壁纸
     * @return
     */
    @GetMapping("/list/random9")
    public BaseResponse<PageResultVo<WallPaper>> listWallPaperRandom9() {
//        Long count = wallpaperMapper.selectCount(null);
        Random random = new Random();
//        int pageNum = random.nextInt((int) (count - 15));
        Page<WallPaper> page = wallpaperMapper.selectPage(new Page<>(1, 9), null);
        return ResultUtils.success(new PageResultVo<>(9L, page.getRecords()));
    }


    @GetMapping("/get")
    public BaseResponse getWallpaperVoById(int id) {
        if (id == 0) {
            return ResultUtils.error(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }
        WallPaper wallPapers = wallpaperMapper.selectById(id);
        return ResultUtils.success(wallPapers);
    }

    @PostMapping("/edit")
    public BaseResponse getWallpaperVoById(@RequestBody WallPaper wallPaperClassify) {
        if (wallPaperClassify == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数错误");
        }
        int status = wallpaperMapper.updateById(wallPaperClassify);
        return ResultUtils.success(null, status > 0 ? "更新成功" : "更新失败");
    }


    @DeleteMapping("/delete")
    public BaseResponse deleteWallpaperVo(Long id) {
        if (id == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数错误");
        }
        int i = wallpaperMapper.deleteById(id);
        return ResultUtils.success(null, i > 0 ? "删除成功" : "删除失败");
    }

    /**
     * 校验文件
     *
     * @param multipartFile
     */
    private Boolean validFile(MultipartFile multipartFile) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        System.out.println("文件尺寸:" + fileSize);
        if (fileSize > 3 * 1024 * 1024L) {
            return false;
        }
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        return Arrays.asList("jpg", "png", "jpeg").contains(fileSuffix);
    }
}
